import random
from django.shortcuts import HttpResponse
from agent.login_agent import create_login
import json

#账号登陆
def login(request):
    if request.method == "GET":
        name = request.GET.get('name')
        password = request.GET.get('password')
        #创建一个登录的智能体
        question = f"请登录系统，用户名：{name} , 密码是: {password}"
        answer = create_login(question)
        if "成功" in answer:
            data={
                "code":200,
                "msg":"登录成功"
            }
            return HttpResponse(json.dumps(data))
        else:
            data = {
                "code":500,
                "msg":"登陆失败"
            }
            return HttpResponse(json.dumps(data))

#发送验证码
def send_email(request):
    if request.method == "GET":
        email = request.GET.get('email')
        #随机生成验证码
        code = str(random.randint(100000,999999))
        question = f"向邮箱为:{email}的用户，发送一份邮件，邮件标题是：知识图谱后台系统验证码登录，邮件内容是:{code}"
        answer = create_login(question)
        if "成功" in answer:
            data = {
                "code":200,
                "msg":"发送成功"
            }
            rs = HttpResponse(json.dumps(data))
            #设置cookie
            rs.set_cookie("code",code,max_age=5*60)
            return rs
        else:
            data={
                "code":500,
                "msg":"发送失败"
            }
            return HttpResponse(json.dumps(data))

#验证码登录
def code_login(request):
    if request.method == "GET":
        code = request.GET.get('code')
        #获取cookie
        cookie_code = request.COOKIES.get('code')
        if not cookie_code:#验证码不存在或者验证码失效
            data ={
                "code":200,
                "msg":"验证码失效，请重新登录"
            }
            return HttpResponse(json.dumps(data))
        elif code == cookie_code: #验证码是否正确
            data = {
                "code":200,
                "msg":"登录成功"
            }
            return HttpResponse(json.dumps(data))
        else:
            data = {
                "code":500,
                "msg":"验证码不正确"
            }
            return HttpResponse(json.dumps(data))